<script setup>
	import {
		Position,
		Handle,
		useNode,
		useVueFlow
	} from '@vue-flow/core'
	import AiChatSetting from './cnps/AiChatSetting.vue';
    import {
        inject,
        onMounted,
        provide,
        ref,
        watch
    } from "vue";
	import {
		getNodeOutputFieldNames
	} from '../node-def'

	const flow = useVueFlow();

	const props = defineProps(['id', 'data'])
	provide('currentNodeId', props.id);


    const updateNodesData = inject("updateNodesData")
    // 监听props.data的变化
    watch(() => props.data, (newValue, oldValue) => {
        console.log('props.data changed ', newValue);
        updateNodesData();
    }, {
        deep: true
    })

    /** 获取所有前置节点的输出字段，并生成下拉选项 */
    const prevOutputFieldOptions = ref([])


    watch(() => flow.getEdges.value, (newV) => {
        console.debug("监听到edge改动", newV)
        updatePrevOutputFieldOptions(props.id);
    })
    //监听prevOutputFieldOptions
    watch(() => prevOutputFieldOptions.value, (newV) => {
        //如果数组是空值,则清空input的值
        if (newV.length === 0) {
            // inputField.value = null;
            props.data.funcChatConfig.funcCallResultField = null;
            props.data.funcChatConfig.matchFunctionField =null;
        }
    })
    flow.onEdgesChange(events => {
        console.debug("intention init", events)
        if (events.some(item => item.type === 'remove' || item.type === 'add')) {
            prevOutputFieldOptions.value = [];
            updatePrevOutputFieldOptions(props.id);
        }
    })

    function updatePrevOutputFieldOptions(sourceNodeId) {
        const connections = flow.getConnectedEdges(sourceNodeId).filter(edge => edge.targetNode.id == sourceNodeId);
        console.log(connections, "connections")
        // 遍历所有前置连接
        connections.forEach(connection => {
            const sourceNode = connection.sourceNode;
            if (sourceNode) {
                // 获取该类型节点的所有输出字段名称
                const outputFields = getNodeOutputFieldNames(sourceNode.type);

                // 从sourceNode.data中获取对应字段的值
                outputFields.forEach(fieldPath => {
                    // 处理嵌套字段路径，如 "llmConfig.outputField"
                    const value = fieldPath.split('.').reduce((obj, key) => obj && obj[key], sourceNode
                        .data);
                    if (value) {
                        if (prevOutputFieldOptions.value.some(item => item.value === value) == false) {
                            //n-select 跟 jb-seletct 的lable叫法不一样
                            // prevOutputFieldOptions.value.push({
                            //   text: value,
                            //   value: value
                            // });
                            prevOutputFieldOptions.value.push({
                                label: value,
                                value: value
                            });
                        }
                    }
                });
                console.log(prevOutputFieldOptions.value, "知识库搜索的问题数组")
                updatePrevOutputFieldOptions(connection.source)

            }
        });

    }

    /** 获取所有前置节点的输出字段，并生成下拉选项 */
    onMounted(() => {
        updatePrevOutputFieldOptions(props.id); //1.初始化的修改数组
    })
</script>

<template>
	<div class="_container">
		<div class="fx fx-c_center pad-16 header">
			<div class="fx fx-center wh-40 logo">
				<jb-icon :local="true" icon="quill:chat" width="30" color="#22c55e"></jb-icon>
			</div>
			<div class="ml-10 tc-dark">
				<div>根据Function调用结果回答</div>
				<p class="font-12 tc-assist">结合Function调用的结果,让ai回答用户的问题</p>
			</div>
		</div>
		<div class="form fx-col pad-16 " @mousedown.stop>

			<label>匹配到的Function</label>
			<n-select placeholder="请选择匹配到的function" clearable v-model:value="props.data.funcChatConfig.matchFunctionField"
				:options="prevOutputFieldOptions"></n-select>
			<label>Function执行结果</label>
			<n-select placeholder="请选择Function执行结果" clearable v-model:value="props.data.funcChatConfig.funcCallResultField"
				:options="prevOutputFieldOptions"></n-select>
			<AiChatSetting v-model="props.data.llmConfig"
				:out="['promptTpl','modelType','outputToResponse', 'persistDb']"
				:inner="['systemRole','maxTokens', 'useContext', 'temperature', 'topP', 'topK']"  />


		</div>
		<div class="footer pad-16">
			<p class="tc-gray ">输出字段</p>
			<div class="output mt-8 pad-8 fx fx-c_center fx-m_between">
				<div class="fx fx-c_center">
					<div class="output-flag noshrink"></div>
					<n-input v-model:value="props.data.funcChatConfig.outputField" placeholder="字段名"
						class="tc-gray ml-8 w-140"></n-input>
				</div>
				<span class="tc-assist">AI生成的回答</span>
			</div>
		</div>

		<Handle type="target" :position="Position.Left" />
		<Handle type="source" id="success" :position="Position.Right"
			style="transform: translate(50%, calc(-50% - 30px))" />
		<Handle type="source" id="fail" :position="Position.Right"
			style="transform: translate(50%, calc(-50% + 30px))" />


	</div>
</template>

<style scoped>
	._container {
		background-color: #fff;
		border: 1px solid #e5e7eb;
		border-radius: 12px;
		box-sizing: border-box;
		width: 380px;
		box-shadow: rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0.1) 0px 10px 15px -3px, rgba(0, 0, 0, 0.1) 0px 4px 6px -4px;
	}

	.header,
	.form {
		border-bottom: 1px solid rgb(229, 231, 235);
	}

	.logo {
		background: #dcfce7;
		border-radius: 12px;
	}

	label {
		margin-bottom: 8px;
	}

	label:not(:first-child) {
		margin-top: 16px;
	}

	.output {
		background: rgb(249, 250, 251);
		border-radius: 12px;
	}

	.output-flag {
		width: 8px;
		height: 8px;
		border-radius: 50%;
		background: #22c55e;
	}
</style>